package xrc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import xrc.pojo.User;
import xrc.service.IUserService;
import xrc.utils.CookieUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义用户参数
 */
@Component  // 需要添加到 WebConfig 中注入
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserService userService;

    // 做条件判断 如果符合条件返回true 才会开始执行下面 resolveArgument 方法
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> type = parameter.getParameterType();
        return type == User.class;
    }

    // 如果上面返回结果为true 则执行此方法 此方法作用主要为实现之前 GoodsController 层的 ticket 条件判断
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        // 通过 webRequest 获取 request
        /*HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

        // 通过 webRequest 获取 response
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);*/
        /*String ticket = CookieUtil.getCookieValue(request, "userTicket");
        if (StringUtils.isEmpty(ticket)) {
            return null; // 如果ticket为空则返回 null
        } else {
            // 如果不为空 则需要从redis中获取用户信息数据
            return userService.getUserByCookie(ticket, request, response);
        }*/
        return UserContext.getUser();
    }
}
